#include <stdlib.h>
#include <string.h>
#include "str.h"


void str_create( str_t *s, int cap)
{
  if ( !s->init )
  {
    s->c = cap;
    s->v = (char*)malloc(sizeof(char)*s->c);
    s->n = 1;
    s->v[0] = '\0';
    s->init = true;
  }
}

void str_free( str_t *s )
{
  if(s->v && s->init)
	{
		s->init = false;
		free(s->v);
	}
}

void str_catc( str_t *s, char c )
{
  if ( s->n == s->c )
  {
    s->c *= 2;
    s->v = (char*)realloc(s->v,sizeof(char)*s->c);
  }
  s->v[s->n-1] = c; 
  s->v[s->n] = '\0';
  s->n++;
}

void str_cats( str_t *s, char *str )
{
  for ( unsigned int i = 0; i < strlen(str); i++ )
    str_catc(s,str[i]);
}

void str_clear( str_t *s )
{
  s->n = 1;
  s->v[0] = '\0';
}

void str_cpy( str_t* dst, str_t* src )
{
  if ( dst->init )
  {
    str_free(dst);
    dst->init = 0;
  }
  str_create(dst,src->n);
  strcpy(dst->v, src->v); //string.h call
  dst->n = src->n;
}

bool is_blank( str_t *s )
{
  bool is_wspace = true;
  for ( int i = 0; i < s->n; i++ )
  {
    char c = s->v[i];
    if ( !( c == ' ' || c == '\t'
          || c == '\n' || c == '\0' ) )
    {
      is_wspace = false;
      break;
    }
  }
  return is_wspace;
}

void str_cpy( str_t* dst, char *src )
{
  int n = strlen(src)+1;
  if ( dst->init )
  {
    str_free(dst);
    dst->init = 0;
  }
  str_create(dst,n);
  strcpy(dst->v, src); //string.h call
  dst->n = n;
}
